<?php

class SrcController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','createquick','update','admin','updatee'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model = new Src;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['Src']))
		{
			$model->attributes=$_POST['Src'];		
			
			if ($model->save()) { $this->generateXML();	}
			else { print_r($model->getErrors()); } 				
			
			if (isset($_POST['addword'])) {
				Yii::app()->user->setState('src', $model->src);
				$this->redirect(array('/words/create'));
			}
			else { $this->redirect(array('/src/admin')); }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}	

	public function generateXML() {
		$sql = "SELECT * FROM tbl_src";
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql);
		$dataReader = $command->query();
		$rows = $dataReader->readAll();
		
		$xml = new domdocument("1.0", "Windows-1251");
		$xml->formatOutput = true;
		
		$root = $xml->createElement("settings");
		$xml->appendChild($root);	
		
		foreach ($rows as $v) 
		{	
			$active_s = $xml->createElement("active");
			$activeText_s = $xml->createTextNode($v['active']);
			$active_s->appendChild($activeText_s);
			
			$d_start = $xml->createElement("d_start");
			$d_startText = $xml->createTextNode($v['d_start']);
			$d_start->appendChild($d_startText);						
			
			$d_end = $xml->createElement("d_end");
			$d_endText = $xml->createTextNode($v['d_end']);
			$d_end->appendChild($d_endText);	
			
			$src = $xml->createElement("src");
			$srcText = $xml->createTextNode($v['src']);
			$src->appendChild($srcText);		

			$site = $xml->createElement("site");
			$siteText = $xml->createTextNode($v['site']);
			$site->appendChild($siteText);
		
			$item = $xml->createElement("item");
			$item->appendChild($active_s);							
			$item->appendChild($d_start);							
			$item->appendChild($d_end);							
			$item->appendChild($src);
			$item->appendChild($site);						
			
			$sqlw = "SELECT * FROM tbl_words WHERE src='".$v['src']."'";
			$commandw = $connection->createCommand($sqlw);
			$dataReaderw = $commandw->query();
			$rowsw = $dataReaderw->readAll();	
			
			$key_words = $xml->createElement("key_words");
			
			foreach ($rowsw as $vw) 
			{								
				$active = $xml->createElement("active_w");
				$activeText = $xml->createTextNode($vw['active_w']);
				$active->appendChild($activeText);		

				$date_start = $xml->createElement("d_start_w");
				$date_startText = $xml->createTextNode($vw['d_start_w']);
				$date_start->appendChild($date_startText);							
				
				$date_end = $xml->createElement("d_end_w");
				$date_endText = $xml->createTextNode($vw['d_end_w']);
				$date_end->appendChild($date_endText);		

				$country = $xml->createElement("country");
				$countryText = $xml->createTextNode($vw['country']);
				$country->appendChild($countryText);		
				
				$region = $xml->createElement("region");
				$regionText = $xml->createTextNode($vw['region']);
				$region->appendChild($regionText);					

				$city = $xml->createElement("city");
				$cityText = $xml->createTextNode($vw['city']);
				$city->appendChild($cityText);					

				$geo_inv = $xml->createElement("geot_invert");
				$geo_invText = $xml->createTextNode($vw['geot_invert'] == '0' ? "" : $vw['geot_invert']);
				$geo_inv->appendChild($geo_invText);				

				$title = $xml->createElement("title");
				$titleText = $xml->createTextNode($vw['title']);
				$title->appendChild($titleText);	
				
				$title_ex = $xml->createElement("title_ex");
				$titleText_ex = $xml->createTextNode($vw['title_ex']);
				$title_ex->appendChild($titleText_ex);					
				
				$type = $xml->createElement("type");
				$typeText = $xml->createTextNode($vw['type']);
				$type->appendChild($typeText);		

				$source = $xml->createElement("source");
				$sourceText = $xml->createTextNode($vw['source']);
				$source->appendChild($sourceText);					

				$target = $xml->createElement("target");
				$targetText = $xml->createTextNode($vw['target']);
				$target->appendChild($targetText);	

				$word = $xml->createElement("word");						
				$word->appendChild($active);	
				$word->appendChild($date_start);	
				$word->appendChild($date_end);	
				$word->appendChild($country);
				$word->appendChild($region);
				$word->appendChild($city);	
				$word->appendChild($geo_inv);				
				$word->appendChild($title);	
				$word->appendChild($title_ex);
				$word->appendChild($type);	
				$word->appendChild($source);	
				$word->appendChild($target);	
				
				$key_words->appendChild($word);	
			}						
			$item->appendChild($key_words);		
			$root->appendChild($item);
		}	
		
		$fileContents = $xml->saveHTML();
        $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        $simpleXml = simplexml_load_string($fileContents);
		$json = json_encode($simpleXml);
		
		$file = Yii::getPathOfAlias('webroot.images.uploads').'/settings.json';
		file_put_contents($file, $json); 
		
		//$xml->save(Yii::getPathOfAlias('webroot.images.uploads').'/settings.xml');	
	}
	
	public function actionCreatequick()
	{
		$model=new Src;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if($model->save()) {
			$this->generateXML();
			$this->redirect(array('/src/admin'));
		}
	}		
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Src']))
		{
			$model->attributes=$_POST['Src'];
			if($model->save()) {
				$this->generateXML();
				$this->redirect(array('/src/admin'));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	public function actionUpdatee() 
	{	
		$es = new EditableSaver('Src'); 
		$es->update();	
		$this->generateXML();	
	}		

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();
		$this->generateXML();	

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Src');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Src('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Src']))
			$model->attributes=$_GET['Src'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Src::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='src-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	protected function checkResultSite($data,$row)
	{
		$res = '';
		switch ($data->site) {
			case '':
				$res = "Выбрать";
				break;
			case 're':
				$res = "Время электроники";
				break;
			case 'elcom':
				$res = "ЭЛ компоненты";
				break;
			case 'light':
				$res = "Светотехника";
				break;				
			case 'jer':
				$res = "ЖЭР";
				break;
		}
		return $res;
	}	
	
	protected function checkResultManager($data,$row)
	{
		$res = '';
		switch ($data->manager) {
			case '':
				$res = "Выбрать";
				break;		
			case 'popova':
				$res = "Попова";
				break;
			case 'jivova':
				$res = "Живова";
				break;
			case 'denisov':
				$res = "Денисов";
				break;	
			case 'baraeva':
				$res = "Бараева";
				break;
			case 'fattahova':
				$res = "Фаттахова";
				break;	
			case 'vasilyeva':
				$res = "Васильева";
				break;				
		}
		return $res;
	}
	
	protected function checkResultActive($data,$row)
	{
		$res = '';
		switch ($data->active) {
			case '':
				$res = "Выбрать";
				break;
			case '1':
				$res = "Вкл.";
				break;
			case '0':
				$res = "Выкл.";
				break;								
		}
		return $res;
	}	
}
